<template>
  <div class="mobile-info-center">
    <van-nav-bar 
      title="信息处理中心" 
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <van-button size="small" type="danger" @click="handleLogout">退出</van-button>
      </template>
    </van-nav-bar>
    <div class="content">
      <!-- 统计卡片 -->
      <div class="stats-section">
        <van-grid :column-num="2" :gutter="16">
          <van-grid-item>
            <div class="stat-card">
              <div class="stat-number">{{ stats.totalResponses }}</div>
              <div class="stat-label">总回复数</div>
            </div>
          </van-grid-item>
          <van-grid-item>
            <div class="stat-card">
              <div class="stat-number">{{ stats.pendingResponses }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </van-grid-item>
          <van-grid-item>
            <div class="stat-card">
              <div class="stat-number">{{ stats.completedResponses }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </van-grid-item>
          <van-grid-item>
            <div class="stat-card">
              <div class="stat-number">{{ stats.avgResponseTime }}</div>
              <div class="stat-label">平均处理时间(小时)</div>
            </div>
          </van-grid-item>
        </van-grid>
      </div>
      <!-- 功能菜单 -->
      <div class="menu-section">
        <van-cell-group inset>
          <van-cell 
            title="数据导出" 
            icon="down" 
            is-link 
            @click="handleDataExport"
          />
          <van-cell 
            title="数据分析" 
            icon="chart-trending-o" 
            is-link 
            @click="handleDataAnalysis"
          />
          <van-cell 
            title="批量处理" 
            icon="setting-o" 
            is-link 
            @click="handleBatchProcess"
          />
          <van-cell 
            title="数据清理" 
            icon="delete-o" 
            is-link 
            @click="handleDataCleanup"
          />
        </van-cell-group>
      </div>
      <!-- 最近活动 -->
      <div class="activity-section">
        <div class="section-title">最近活动</div>
        <van-cell-group inset>
          <van-cell 
            v-for="activity in recentActivities" 
            :key="activity.id"
            :title="activity.title"
            :label="activity.description"
            :value="formatTime(activity.time)"
          >
            <template #icon>
              <van-icon 
                :name="activity.icon" 
                :color="activity.color"
                size="20"
                style="margin-right: 8px;"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      <!-- 快捷操作 -->
      <div class="quick-actions">
        <van-button 
          type="primary" 
          block 
          @click="handleQuickProcess"
          :loading="processing"
        >
          {{ processing ? '处理中...' : '一键处理待办事项' }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast, showConfirmDialog } from 'vant'
import useUserStore from '@/store/modules/user'
import { listAnswer, delAnswer, exportAnswer } from '@/api/questionnaire'
import { saveAs } from 'file-saver'

const router = useRouter()
const userStore = useUserStore()
const processing = ref(false)

// 统计数据
const stats = reactive({
  totalResponses: 0,
  pendingResponses: 0,
  completedResponses: 0,
  avgResponseTime: 0
})

// 最近活动
const recentActivities = ref([])

// 获取答卷数据并统计
async function fetchStatsAndActivities() {
  try {
    const res = await listAnswer({})
    const answers = res.rows || []
    stats.totalResponses = answers.length
    // 假设status字段: 0=待处理, 1=已完成
    stats.pendingResponses = answers.filter(a => a.status === 0).length
    stats.completedResponses = answers.filter(a => a.status === 1).length
    // 平均处理时间（以submitTime和createTime差值为例，单位小时）
    const times = answers
      .filter(a => a.status === 1 && a.createTime && a.submitTime)
      .map(a => (new Date(a.submitTime) - new Date(a.createTime)) / 3600000)
    stats.avgResponseTime = times.length ? (times.reduce((a, b) => a + b, 0) / times.length).toFixed(2) : 0
    // 最近活动（取最近5条）
    recentActivities.value = answers.slice(0, 5).map(a => ({
      id: a.id,
      title: a.status === 0 ? '新回复待处理' : '答卷已完成',
      description: a.questionnaireTitle || '',
      time: a.submitTime ? new Date(a.submitTime) : new Date(),
      icon: a.status === 0 ? 'bell' : 'success',
      color: a.status === 0 ? '#fa8c16' : '#52c41a'
    }))
  } catch (e) {
    showToast('获取数据失败')
  }
}

// 数据导出
async function handleDataExport() {
  try {
    const res = await exportAnswer({})
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    saveAs(blob, '答卷数据.xlsx')
  } catch (e) {
    showToast('导出失败')
  }
}

// 数据分析
function handleDataAnalysis() {
  showToast('请前往统计页面查看详细分析')
}

// 批量处理（示例：批量标记为已完成）
async function handleBatchProcess() {
  try {
    const res = await listAnswer({ status: 0 })
    const ids = (res.rows || []).map(a => a.id)
    if (!ids.length) return showToast('暂无待处理项')
    // 这里只做批量删除示例，实际可根据业务调整
    await delAnswer(ids.join(','))
    showSuccessToast('批量处理完成')
    fetchStatsAndActivities()
  } catch (e) {
    showToast('批量处理失败')
  }
}

// 数据清理（示例：清理无效答卷）
async function handleDataCleanup() {
  try {
    await showConfirmDialog({
      title: '确认清理',
      message: '确定要清理所有待处理答卷吗？此操作不可恢复。'
    })
    const res = await listAnswer({ status: 0 })
    const ids = (res.rows || []).map(a => a.id)
    if (!ids.length) return showToast('无待处理数据')
    await delAnswer(ids.join(','))
    showSuccessToast('清理完成')
    fetchStatsAndActivities()
  } catch (e) {}
}

// 一键处理
async function handleQuickProcess() {
  await handleBatchProcess()
}

// 格式化时间
function formatTime(date) {
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  return `${days}天前`
}

// 退出登录
async function handleLogout() {
  try {
    await showConfirmDialog({
      title: '确认退出',
      message: '确定要退出登录吗？退出后需要重新登录。'
    })
    showToast({ message: '正在退出...', duration: 0, forbidClick: true })
    await userStore.logOut()
    const Cookies = await import('js-cookie')
    Cookies.default.remove('username')
    Cookies.default.remove('password')
    Cookies.default.remove('rememberMe')
    localStorage.removeItem('vuex')
    sessionStorage.clear()
    showSuccessToast('退出成功')
    setTimeout(() => { router.push('/mobile-login') }, 1000)
  } catch (error) {
    if (error) {
      console.error('退出登录失败:', error)
      showToast('退出失败，请重试')
    }
  }
}

// 返回上一页
function goBack() {
  router.back()
}

onMounted(() => {
  // 未登录强制跳转到登录页
  if (!userStore.token) {
    router.replace('/mobile-login')
    return
  }
  fetchStatsAndActivities()
})
</script>

<style scoped>
.mobile-info-center {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content {
  padding: 20px;
  padding-top: 20px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 90px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  width: 100%;
  min-width: 0;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.menu-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  padding-left: 4px;
}

.activity-section {
  margin-bottom: 32px;
}

.quick-actions {
  margin-top: 20px;
}

/* 自定义 Vant 组件样式 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.van-nav-bar__text) {
  color: white;
}

:deep(.van-nav-bar .van-button) {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 14px;
}

:deep(.van-cell-group--inset) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.van-cell) {
  padding: 16px 20px;
  font-size: 16px;
}

:deep(.van-cell__title) {
  font-weight: 500;
  color: #333;
}

:deep(.van-cell__label) {
  color: #666;
  font-size: 14px;
  margin-top: 4px;
}

:deep(.van-cell__value) {
  color: #999;
  font-size: 12px;
}

:deep(.van-grid-item__content) {
  background: transparent;
  padding: 0;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .content {
    padding: 16px;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  :deep(.van-cell) {
    padding: 14px 16px;
    font-size: 15px;
  }
}
</style> 